package com.medaxis.hpams.sso.service.impl;



import com.medaxis.hpams.dto.global.ErrorException;
import com.medaxis.hpams.sso.domain.dto.LoginUser;
import com.medaxis.hpams.sso.domain.dto.UserDto;
import com.medaxis.hpams.sso.myenum.UserStatus;
import com.medaxis.hpams.sso.service.UserService;
import com.medaxis.hpams.sso.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDto userDto = userService.selectUserByUserName(username);
        if (StringUtils.isNull(userDto)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(userDto.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ErrorException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(userDto.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ErrorException("对不起，您的账号：" + username + " 已停用");
        }

        return createLoginUser(userDto);
    }

    public UserDetails createLoginUser(UserDto userDto) {
        return new LoginUser(userDto, permissionService.getMenuPermission(userDto));
    }
}
